﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Yunzuan.Foundation.Web
{
    /// <summary>
    /// Session管理器
    /// </summary>
    public class SessionManager
    {
        /// <summary>
        /// 获取Session值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="key">SessionName</param>
        /// <returns></returns>
        public static T GetSession<T>(string sessionName)
        {
            if (HttpContext.Current.Session[sessionName] != null)
            {
                try
                {
                    return (T)HttpContext.Current.Session[sessionName];
                }
                catch
                {
                    return default(T);
                }
            }
            return default(T);
        }

        /// <summary>
        /// 取Session中存储的对象
        /// </summary>
        /// <remarks>
        /// 非特殊情况，不要向Session中存储复杂对象
        /// </remarks>
        /// <typeparam name="T"></typeparam>
        /// <param name="sessionName"></param>
        /// <returns></returns>
        public static T GetSessionObject<T>(string sessionName) where T : class, new()
        {
            if (HttpContext.Current.Session[sessionName] != null)
            {
                try
                {
                    return (T)HttpContext.Current.Session[sessionName];
                }
                catch
                {
                    return default(T);
                }
            }
            return new T();
        }

        /// <summary>
        /// 获取Session值
        /// </summary>
        /// <param name="sessionName">SessionName</param>
        /// <returns></returns>
        public static string GetSession(string sessionName)
        {
            if (HttpContext.Current.Session[sessionName] != null)
            {
                return HttpContext.Current.Session[sessionName] as string;
            }
            return string.Empty;
        }

        /// <summary>
        /// 设置Session
        /// </summary>
        /// <param name="sessionName">SessionName</param>
        /// <param name="value">Session值</param>
        public static void SetSession(string sessionName, object value)
        {
            HttpContext.Current.Session[sessionName] = value;
        }

        /// <summary>
        /// 移除Session
        /// </summary>
        /// <param name="sessionName">SessionName</param>
        public static void RemoveSession(string sessionName)
        {
            HttpContext.Current.Session.Remove(sessionName);
        }

        /// <summary>
        /// 清除全部Session
        /// </summary>
        /// <returns></returns>
        public static void ClearSession()
        {
            HttpContext.Current.Session.RemoveAll();
        }
    }
}
